package com.sx.pipeline.ui.area

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.permissionx.guolindev.PermissionX
import com.sx.mvvmlibs.binding.edittext.viewAdapter
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYBaseAppBarActivity
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActImportFilesBinding
import java.io.File


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 导入文件
 */
@Route(path = RoutePath.Mine.IMPORT_FILES)
class ImportFilesActivity :
    CYBaseAppBarActivity<ActImportFilesBinding, ImportFileVM>(R.layout.act_import_files),
    View.OnClickListener {

    private lateinit var mPopup: BasePopupView

    private var fileName: String = ""

    override fun initAppBar() {
        getTitleBar().title = "导入区域文件"
    }

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_confirm -> {
                if (!TextUtils.isEmpty(fileName)) {
                    showInputDialog()
                } else {
                    ToastUtils.showShort("请输入文件名称")
                }
            }
            R.id.ll_import -> {
                requestPermission()
            }
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        // kml文件数据
        observe(mViewModel.fileBeanListEvent) { data ->
            mBinding.tvImport.visibility = View.GONE
            mBinding.imageFile.visibility = View.VISIBLE
            Logs.d("kmlBeanListEvent ${data!!.size}")
        }

        // dxf文件数据
        observe(mViewModel.dxfBeanListEvent) {
            mBinding.tvImport.visibility = View.GONE
            mBinding.imageFile.setImageDrawable(getDrawable(R.drawable.ic_dxf_file))
            mBinding.imageFile.visibility = View.VISIBLE
            Logs.d("dxfBeanListEvent ${it!!.size}")
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Logs.d("onActivityResult $resultCode")
        if (resultCode != RESULT_OK) {
            return
        } else if (requestCode == 1000) {
            if (data != null) {
                val uri: Uri = data.data!!
                val file: File = UriUtils.uri2File(uri)
                if (file.name.endsWith(".kml")) {
                    fileName = file.name
                    mViewModel.kmlAnalysis(file)
                } else if (file.name.endsWith(".dxf")) {
                    fileName = file.name
                    mViewModel.dxfAnalysis(file)
                } else {
                    mBinding.tvImport.visibility = View.VISIBLE
                    mBinding.imageFile.visibility = View.GONE
                    ToastUtils.showShort("文件格式错误，请重新导入")
                }

            }
        }

        if (requestCode == REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                openFileManager()
            } else {
                Toast.makeText(this, "存储权限获取失败", Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun openFileManager() {
        // 打开文件管理器选择文件
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        // 类型限制
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivityForResult(intent, 1000)
    }

    private val REQUEST_CODE = 1024
    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= 30) {
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) {
                openFileManager()
            } else {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.data = Uri.parse("package:" + application.packageName)
                startActivityForResult(intent, REQUEST_CODE)
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 先判断有没有权限
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                openFileManager()
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ),
                    REQUEST_CODE
                )
            }
        } else {
            openFileManager()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                openFileManager()
            } else {
                Toast.makeText(this, "存储权限获取失败", Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 输入名称
     */
    private fun showInputDialog() {
        mPopup = XPopup.Builder(this)
            .autoDismiss(false)
            .asInputConfirm(
                "请输入文件名称",
                "", fileName, "文件名称"
            ) {
                if (!TextUtils.isEmpty(it)) {
                    mViewModel.addTerritory(it)
                    mPopup.dismiss()
                } else {
                    ToastUtils.showShort("请输入文件名称")
                }
            }.also {
                val editText = it.findViewById<EditText>(com.lxj.xpopup.R.id.et_input)
                viewAdapter.filterEditText(editText, true)
            }.show()
    }
}